import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/x3_component_core.dart';
import 'package:x3_form_core/provider/base_request_form_provider.dart';
import 'package:x3_form_core/business_components/base_request_form_container.dart';

/// 基本表单
///
class BaseRequestFormInput extends StatefulWidget {
  BaseRequestFormInput({Key key, @required this.request, this.isPassword = false, this.isSaveASingle = false, this.requestSaveData}) : super(key: key);

  final BaseHttpRequestModel request;

  final bool isPassword;

  final bool isSaveASingle;

  final RequestSaveData requestSaveData;

  @override
  _BaseRequestFormInputState createState() => _BaseRequestFormInputState();
}

class _BaseRequestFormInputState extends State<BaseRequestFormInput> {
  BaseRequestFormProvider _baseRequestFormProvider;

  /// 通过焦点消失回调
  FocusNode focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    focusNode.addListener(() {
      if (!focusNode.hasFocus) {
        if (widget.requestSaveData != null) widget.requestSaveData(widget.request, _baseRequestFormProvider.getMapDataSource(widget.request), notShowLoading: true);
        //收回键盘
        FocusScope.of(context).requestFocus(FocusNode());
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    _baseRequestFormProvider = BaseRequestFormProvider.of(context);
    var value = _baseRequestFormProvider.getDataSource(widget.request) ?? '';

    ///处理当传入值为Map的时候，只取Map的最后一个的value显示 -----------
    String valueMap;
    if (value != null && (value is Map)) {
      value.forEach((key, valueString) {
        if (valueString.toString().isNotEmpty) valueMap = valueString.toString();
      });
    }
    if (valueMap != null && valueMap.isNotEmpty) value = valueMap;

    /// ------------------------------------
    return BaseRequestFormContainer(
      request: widget.request,
      child: BaseTextField(
        focusNode: focusNode,
        inputFormatters: _textInputFormatter(),
        keyboardType: _inputShowType(),
        value: (value is String) == true ? value : value.toString(),
        readOnly: _baseRequestFormProvider.isReadonly(widget.request),
        hintText: widget.request.notes,
        obscureText: widget.isPassword,
        emitFocusNode: _focusNodeListener,
        onSubmitted: (String value) {
          if (value.isEmpty && widget.request.required) {
            BaseUtils.showToast("${widget.request.name}不能为空");
            return;
          }
          if (widget.isSaveASingle && widget.isSaveASingle != null) {
            _baseRequestFormProvider.setDataSource(widget.request, value);
            widget.requestSaveData(widget.request, _baseRequestFormProvider.getMapDataSource(widget.request));
          }
        },
        onChanged: (String value) {
          /// 保存值
          _baseRequestFormProvider.setDataSource(widget.request, value);
        },
      ),
    );
  }

  /// 监听焦点
  void _focusNodeListener(FocusNode focusNode) {
    focusNode.addListener(() {
      _baseRequestFormProvider.emitFocusNode(focusNode.hasFocus, widget.request);
    });
  }

  /// 是否数字类型键盘类型
  TextInputType _inputShowType() {
    if (widget.request.inputType == BaseHttpInputTypeEnum.InputNumber) return TextInputType.number;
    if (widget.request.inputType == BaseHttpInputTypeEnum.InputAmount) return TextInputType.numberWithOptions(decimal: true);
    if (widget.request.inputType == BaseHttpInputTypeEnum.InputFloat) return TextInputType.number;
    return null;
  }

  /// 数字限制
  List<TextInputFormatter> _textInputFormatter() {
    if (widget.request.inputType == BaseHttpInputTypeEnum.InputNumber) {
      return [FilteringTextInputFormatter.digitsOnly];
    }

    if (widget.request.inputType == BaseHttpInputTypeEnum.InputAmount || widget.request.inputType == BaseHttpInputTypeEnum.InputFloat) {
      return [FilteringTextInputFormatter.allow(RegExp(r'^([-|\d])?|[\d+|\d.]'))];
    }
    return null;
  }
}
